#pragma once
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <sys/wait.h>
#include <vector>
#include "Task.hpp"
#define NUM 5
using namespace std;
class Channel
{
public:
    Channel(int wfd, int id) : _wfd(wfd), _id(id)
    {}
    void Write(int code)
    {
        write(_wfd,&code,sizeof(code));
    }
    void Close()
    {
        close(_wfd);
    }
    void WaitPid()
    {
        waitpid(_id,nullptr,0);
        cout<<"等待进程"<<_id<<"成功"<<endl;
    }
    ~Channel()
    {}

private:
    int _wfd;
    int _id;
};
class ChannelManage
{
public:
    ChannelManage():_next(0)
    {}
    void Insert(int wfd, int id)
    {
        _channels.emplace_back(wfd, id);
    }
    int GetChannel()//轮询访问子进程
    {
        int tmp = _next;
        _next++;
        _next %= _channels.size();
        return tmp;
    }
    void WriteManage(int code,int index)
    {
        _channels[index].Write(code);
    }
    void CloseAll()
    {
        for(int i=0;i<_channels.size();i++)
        {
            _channels[i].Close();
        }
    }
    void CloseWait()
    {
        for(int i=0;i<_channels.size();i++)
        {
            _channels[i].Close();
            _channels[i].WaitPid();
        }
    }
    ~ChannelManage()
    {}
private:
    vector<Channel> _channels;
    int _next;
};

class ProcessPool
{
public:
    ProcessPool(int num) : _n(num)
    {
        _tm.InsertTask(PrintLog);
        _tm.InsertTask(Download);
        _tm.InsertTask(Upload);
    }
    void Work(int rfd)
    {
        while (true)
        {
            int code;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if(n != sizeof(code)) continue;
                else
                {
                    //执行任务
                    _tm.ExeTask(code);
                }
            }
            else
            {
                cout<<"子进程"<<getpid()<<"退出"<<endl;
                break;
            }
        }
    }
    void Start()
    {
        for (int i = 0; i < _n; i++)
        {
            int pipefd[2];
            pipe(pipefd);
            pid_t id = fork();
            if (id == 0)
            {
                _cm.CloseAll();
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                close(pipefd[0]);
                _cm.Insert(pipefd[1], id);
            }
        }
    }
    void Run()
    {
        int ChannelCode = _cm.GetChannel();
        int TaskCode = _tm.GetCode();
        _cm.WriteManage(TaskCode,ChannelCode);
    }
    void Stop()
    {
        _cm.CloseWait();
    }
    ~ProcessPool()
    {}
private:
    ChannelManage _cm;
    int _n;
    TaskManage _tm;
};
